import { Button, Space, Table, TableProps } from "antd";
import { useEffect, useState } from "react";
import { useLocation } from "react-router-dom";
import RankingList from "./RankingList";
import { useCounter } from "@/model/context";
import { pokerAwardList, pokerAwardS } from "@/service";
import { message } from "antd";

const getColums = ({
  claimReward,
  loadingId,
}: {
  claimReward: (id: number) => void;
  loadingId: number | null;
}) => {
  const columns: TableProps<any>["columns"] = [
    {
      title: "活动名称",
      dataIndex: "activateName",
      key: "activateName",
      align: "center",
      width: 200,
    },
    {
      title: "材料名称",
      dataIndex: "goodName",
      key: "goodName",
      align: "center",
      width: 200,
    },
    {
      title: "数量",
      dataIndex: "num",
      key: "num",
      align: "center",
      width: 50,
    },

    {
      title: "操作",
      key: "action",
      fixed: "right",
      align: "center",
      width: 150,
      render: (v: any, record: any) => (
        <Space size="middle">
          {record?.isEnd === 0 && (
            <Button
              type="primary"
              onClick={() => claimReward(record?.id)}
              disabled={loadingId === record.id}
              loading={loadingId === record.id}
            >
              {loadingId === record.id ? "领取中..." : "领取"}
            </Button>
          )}
          {record?.isEnd === 1 && <Button disabled>已领取</Button>}
        </Space>
      ),
    },
  ];
  return columns;
};

const History = () => {
  const location = useLocation();
  const { state: { serverId } } = useCounter();
  const [tableConfig, setTableConfig] = useState({
    dataSource: [],
  });
  const [open, setOpen] = useState(false);
  const [loadingId, setLoadingId] = useState<number | null>(null); // 记录加载中的 id

  useEffect(() => {
    const queryParams = new URLSearchParams(location.search);
    const taskId = queryParams.get("taskId");
    getActiveList({ taskId });
  }, [location.search]);

  const getActiveList = async (params: any) => {
    const res = await pokerAwardList(params);
    setTableConfig({
      dataSource: res?.content || [],
    });
  };

  const claimReward = async (id: number) => {
    setLoadingId(id); // 设置当前领取的 id 为 loading
    try {
      const res = await pokerAwardS({
        serverId,
        awardId: id,
      });

      if (res) {
        const queryParams = new URLSearchParams(location.search);
        const taskId = queryParams.get("taskId");
        getActiveList({ taskId }); // 刷新数据
      }
    } catch (error) {
      message.error("领取失败，请重试。");
    } finally {
      setLoadingId(null); // 清除 loading 状态
    }
  };

  const selectRanking = () => {
    setOpen(true);
  };

  return (
    <>
      <div className="historyPage">
        <Table
          dataSource={tableConfig.dataSource}
          rowKey={(record) => record.id}
          scroll={{
            y: 550,
            x: "100%",
          }}
          columns={getColums({ claimReward, loadingId })}
          pagination={{
            position: ["bottomCenter"],
            total: 0,
            current: 1,
            pageSize: 10,
            pageSizeOptions: ["10", "20", "50", "100"],
            showSizeChanger: true,
            showTotal: (total: number) => `共 ${total} 条数据`,
          }}
        />
      </div>
      <RankingList open={open} setOpen={setOpen} />
    </>
  );
};

export default History;